﻿using Common.Contract;
using Common.Contract.Authentication.Record;
using Common.Contract.ProductHandbook.Request;
using Common.Service.Command;
using Common.Util;
using CrossSelling.Model.Interface;
using CrossSelling.Model.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace CrossSelling.Core.ServiceCommand
{
    public class UpdateCustomerChecklistServiceCommand : ProviderServiceCommand<IProviderFactory, UpdateCustomerChecklistRequest, ResponseRecord>
    {
        private UserRecord Dao;
        public UpdateCustomerChecklistServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(UpdateCustomerChecklistRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.DataUpdate.IsNullOrEmpty())
            {
                throw new ArgumentException("Record must be set", "request");
            }
            if (request.DaoChange == null)
            {
                throw new ArgumentException("MSBO Dao must be set", "request");
            }
            else
            {
                Dao = Request.DaoChange;
            }
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            try
            {
                bool isUpdate = true;
                var array = JArray.Parse(Request.DataUpdate);
                if (Request.SubProductId != 0)
                {
                    var custUpdate = JArray.Parse(array[0].ToString().Trim('{', '}'));
                    var firstDoc = JArray.Parse(array[1].ToString().Trim('{', '}'));
                    string firstDoc1 = firstDoc[0].ToString();
                    int firstDocId = int.Parse(Regex.Replace(firstDoc1, "[^0-9]+", string.Empty));

                    int productId = Providers.ProductHandbooks.RetrieveProductIdByDocumentId(firstDocId, Request.SubProductId);
                    if (productId > 0)
                    {
                        ChecklistCustomer customer = new ChecklistCustomer
                        {
                            Cif = custUpdate[0].ToString(),
                            CustName = custUpdate[1].ToString(),
                            LegalId = custUpdate[2].ToString(),
                            DateUpdate = DateTime.Now,
                            DateAdd = DateTime.Now,
                            Dao = Dao.Dao,
                            DaoName = Dao.FullName,
                            Region = Dao.Zone,
                            Branch = Dao.Branch,
                            Ccid = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
                            ProductId = productId,
                            SubProductId = Request.SubProductId
                        };
                        List<ChecklistDocumentByCustomer> listDocDocument = new List<ChecklistDocumentByCustomer>();
                        for (int i = 1; i < array.Count; i++)
                        {
                            firstDoc = JArray.Parse(array[i].ToString().Trim('{', '}'));
                            firstDoc1 = firstDoc[0].ToString();
                            firstDocId = int.Parse(Regex.Replace(firstDoc1, "[^0-9]+", string.Empty));
                            ChecklistDocumentByCustomer docCustomer = new ChecklistDocumentByCustomer
                            {
                                Ccid = customer.Ccid,
                                DocumentId = firstDocId,
                                CreatedDate = DateTime.Now,
                                Status = firstDoc[1].ToString().ToLower().Equals("false") ? 0 : 1
                            };
                            listDocDocument.Add(docCustomer);
                        }
                        isUpdate = Providers.ProductHandbooks.SaveCustomerChecklist(customer, listDocDocument);
                    }
                }
                else if (!string.IsNullOrEmpty(Request.Ccid))
                {
                    ChecklistCustomer checklistCustomer = Providers.ProductHandbooks.RetrieveCustomerChecklistByCcid(int.Parse(Request.Ccid), Dao);
                    if (checklistCustomer != null)
                    {
                        List<ChecklistDocumentByCustomer> listDocDocument = new List<ChecklistDocumentByCustomer>();
                        var firstDoc = JArray.Parse(array[1].ToString().Trim('{', '}'));
                        string firstDoc1 = firstDoc[0].ToString();
                        int firstDocId = int.Parse(Regex.Replace(firstDoc1, "[^0-9]+", string.Empty));
                        for (int i = 0; i < array.Count; i++)
                        {
                            firstDoc = JArray.Parse(array[i].ToString().Trim('{', '}'));
                            firstDoc1 = firstDoc[0].ToString();
                            firstDocId = int.Parse(Regex.Replace(firstDoc1, "[^0-9]+", string.Empty));
                            ChecklistDocumentByCustomer docCustomer = new ChecklistDocumentByCustomer
                            {
                                Ccid = int.Parse(Request.Ccid),
                                DocumentId = firstDocId,
                                CreatedDate = DateTime.Now,
                                Status = firstDoc[1].ToString().ToLower().Equals("false") ? 0 : 1
                            };
                            listDocDocument.Add(docCustomer);
                        }
                        checklistCustomer.DateUpdate = DateTime.Now;
                        Dictionary<int, ChecklistDocumentByCustomer> dicDocDocument = listDocDocument.ToDictionary(x => x.DocumentId);
                        isUpdate = Providers.ProductHandbooks.UpdateCustomerChecklist(checklistCustomer, dicDocDocument);
                    }
                }

                return isUpdate;
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
    }
}
